package org.balthie.demo.jdk.thread.threadlocal;

import java.util.WeakHashMap;

public class ThreadLocalDemo {
//	为什么ThreadLocal要声明为 static
//	https://blog.csdn.net/qq_40649503/article/details/115795510
//	坏处是这样做可能正好形成内存泄漏所需的条件 https://www.zhihu.com/question/35250439
	private static ThreadLocal<String> staticThreadLocal = new ThreadLocal<>();
	
	public static void main(String[] args) {
		staticThreadLocal.set("static mainThread TL value");
		ThreadLocal<String> threadLocal = new ThreadLocal<>();
		threadLocal.set("normal mainThread TL value");
		System.out.println(Thread.currentThread() + " 主线程 static TL value:" + staticThreadLocal.get() + " normal TL value:" + threadLocal.get());
//		解除强引用
		threadLocal = null;
		
		Thread subThread = new Thread(new Runnable() {
			@Override
			public void run() {
				for(int i=0;i<5;i++)
				{
					String value = staticThreadLocal.get();
					System.out.println(Thread.currentThread() + " 子线程 static TL value:" + value);
					
					try {
						Thread.sleep(300);
					} catch (InterruptedException e) {
					}
				}
			}
		});
		subThread.start();
		
		System.gc();
		
		try {
			Thread.sleep(500);
		} catch (InterruptedException e) {
		}
		System.out.println(Thread.currentThread() + " 主线程 value:" + staticThreadLocal.get() + " normal TL value:" + threadLocal.get());
		
	}
}